import React, { Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Card, Form, Divider, Tag, Col, Row, DatePicker, Select, Input } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ProductLisForm from './component/ProductListForm';

import styles from '../../styles/Manage.less';

const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// 日期
const currentDay = moment(new Date(new Date().getTime()));

@Form.create()
@connect(({ marketNight, loading }) => ({
  marketNight,
  loading: loading.models.marketNight,
}))
class NightManage extends React.Component {
  state = {
    cityId: '-1',
    cities: [],
    activityType: -1,
    storeName: '',
    date: currentDay, //
    dateString: currentDay.format('YYYY-MM-DD'),
    modalVisible: false,
    cityProductIds: [],
  };

  // 表格字段
  columns = [
    {
      title: '日期',
      width: 160,
      fixed: 'left',
      align: 'center',
      render: (text, record) => <span>{record.date}</span>,
    },
    {
      title: '活动类型',
      width: 120,
      dataIndex: 'activityType',
      render: text =>
        text === 1 ? <Tag color="green">门店级别</Tag> : <Tag color="cyan">城市级别</Tag>,
    },
    { title: '活动名称', width: 120, dataIndex: 'activityName' },
    { title: '活动Id', width: 120, dataIndex: 'activityId' },
    { title: '城市', width: 120, dataIndex: 'cityId' },
    { title: '折扣', width: 120, dataIndex: 'reduceDiscount' },
    { title: '门店Id', width: 120, dataIndex: 'storeId' },
    { title: '门店名称', width: 120, dataIndex: 'storeName' },
    {
      title: '创建时间',
      width: 100,
      dataIndex: 'created',
      render: text => <span>{moment.unix(text).format('HH:mm')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      fixed: 'right',
      align: 'center',
      width: 90,
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>商品列表</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.handleSearch();
    this.getCities();
  }

  handleModalVisible = (flag, record) => {
    let cityProductIds = [];
    if (record && record.cityProductIdList) {
      cityProductIds = record.cityProductIdList.split(',');
    }
    console.log(cityProductIds);
    this.setState({
      modalVisible: !!flag,
      cityProductIds,
    });
  };

  getCities = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'commonInfo/fetchByClassify',
      payload: {
        classify: 'city',
      },
      callback: data => {
        const list = [];
        data.forEach(item => {
          list.push({
            code: item.code,
            name: item.name,
          });
        });
        this.setState({
          cities: list,
        });
      },
    });
  };

  getQueryParams = () => {
    const { dateString, cityId, activityType, storeName } = this.state;
    const params = {};
    if (cityId !== '-1') {
      params.cityId = cityId;
    }
    if (activityType !== -1) {
      params.activityType = activityType;
    }
    if (dateString) {
      params.date = dateString;
    }
    if (storeName) {
      params.storeName = storeName;
    }
    return params;
  };

  // 查询操作
  handleSearch = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    dispatch({
      type: 'marketNight/fetch',
      payload: {
        params,
      },
      callback: () => {},
    });
  };

  // 动态修改折扣
  doDynamicAdjust = params => {
    const { dispatch } = this.props;
    dispatch({
      type: 'marketNight/doDynamicAdjust',
      payload: {
        ...params,
      },
      callback: () => {
        this.setState({
          modalVisible: false,
        });
        this.handleSearch();
      },
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const queryParams = this.getQueryParams();

    const params = {
      ...formValues,
      ...filters,
      ...queryParams,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'marketNight/fetch',
      payload: {
        params,
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      marketNight: { data },
    } = this.props;
    const { date, cityId, activityType, cities, modalVisible, cityProductIds } = this.state;

    let totalWidth = 0;
    this.columns.forEach(col => {
      const { width } = col;
      if (width) {
        totalWidth += width;
      }
    });

    return (
      <PageHeaderWrapper title="夜市活动" content="参数夜市活动的相关信息">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem key="date" label="日期">
                      {getFieldDecorator('date', {
                        initialValue: date,
                      })(
                        <DatePicker
                          onChange={(dateNew, dateString) => {
                            this.setState(
                              {
                                date: dateNew,
                                dateString,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                          placeholder="选择日期"
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="cityId" label="城市">
                      {getFieldDecorator('cityId', {
                        initialValue: cityId,
                      })(
                        <Select
                          key="cityId"
                          placeholder="请选择城市"
                          showSearch
                          optionFilterProp="children"
                          onChange={value => {
                            this.setState(
                              {
                                cityId: value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {cities.map(item => (
                            <Option key={item.code} value={item.code}>
                              {item.name}({item.code})
                            </Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="activityType" label="活动类型">
                      {getFieldDecorator('activityType', {
                        initialValue: activityType,
                      })(
                        <Select
                          placeholder="请选择类型"
                          onChange={value => {
                            this.setState(
                              {
                                activityType: value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          <Option key={-1} value={-1}>
                            全部
                          </Option>
                          <Option key={0} value={0}>
                            城市级别
                          </Option>
                          <Option key={1} value={1}>
                            门店级别
                          </Option>
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="storeName" label="门店名称">
                      {getFieldDecorator('storeName', {})(
                        <Input
                          placeholder="请选择类型"
                          onChange={e => {
                            this.setState(
                              {
                                storeName: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
            <Divider type="horizontal" />
            <StandardTable
              loading={loading}
              data={data}
              scroll={{ x: totalWidth }}
              columns={this.columns}
              rowKey={record => record.id}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {modalVisible && (
          <ProductLisForm
            modalVisible={modalVisible}
            idList={cityProductIds}
            handleModalVisible={() => {
              this.setState({
                modalVisible: false,
              });
            }}
          />
        )}
      </PageHeaderWrapper>
    );
  }
}

export default NightManage;
